package com.whsxt.controller;

import com.whsxt.common.AjaxResult;
import com.whsxt.utils.FileUploadUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/uploadImg.do")
    public AjaxResult uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        // 获取上传的文件路径
        String projectPath = FileUploadUtil.getProjectPath();
        String uploadPath = FileUploadUtil.getUploadPath(projectPath, file.getOriginalFilename());
        // 通过路径,输入输出流创建文件
        File uploadFile = new File(projectPath + uploadPath);
        // 得到输入输出流
        InputStream inputStream = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(uploadFile);
        // 读写文件
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = (inputStream.read(buf))) != -1){
            fos.write(buf, 0, len);
        }
        fos.flush();
        fos.close();
        inputStream.close();

        return AjaxResult.ok(uploadPath);
    }
}
